<template>
  <div>
    <!-- 统计区域 start -->
    <a-card :bordered="false" style="margin-bottom: 10px">
      <a-row type="flex" justify="space-around" align="middle">
        <a-col :span="6">
          <a-select allowClear showArrow style="width: 80%" v-model="modelSelect" placeholder="模型选择" @change="getStateCount">
            <a-select-option v-for="model in modelOptions" :key="model.id">
              {{ model.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-statistic title="全部设备" :value="stateCount.all" />
        </a-col>
        <a-col :span="4">
          <a-statistic :value="stateCount.online">
            <template #title>
              <a-icon type="check-circle" theme="twoTone" two-tone-color="#52c41a" />
              在线
            </template>
          </a-statistic>
        </a-col>
        <a-col :span="4">
          <a-statistic :value="stateCount.offline">
            <template #title>
              <a-icon type="close-circle" theme="twoTone" two-tone-color="red" />
              离线
            </template>
          </a-statistic>
        </a-col>
        <a-col :span="4">
          <a-statistic :value="stateCount.notAction">
            <template #title>
              <a-icon type="stop" theme="outlined" two-tone-color="#808080" />
              未激活
            </template>
          </a-statistic>
        </a-col>
        <a-col :span="2">
          <a-button @click="getStateCount(modelSelect)">刷新</a-button>
        </a-col>
      </a-row>
    </a-card>
    <!-- 统计区域 END -->
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
              <a-form-item label="实例名称">
                <a-input v-model="queryParam.name" placeholder="请输入实例名称"></a-input>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus">
              <a-col :lg="7" :md="8" :sm="24" :xl="6">
                <a-form-item label="实例标识">
                  <a-input v-model="queryParam.code" placeholder="请输入实例标识"></a-input>
                </a-form-item>
              </a-col>
            </template>
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
              <span class="table-page-search-submitButtons" style="float: left;overflow: hidden;">
                <a-button icon="search" type="primary" @click="searchQuery">查询</a-button>
                <a-button icon="reload" style="margin-left: 8px" type="primary" @click="searchReset">重置</a-button>
                <a style="margin-left: 8px" @click="handleToggleSearch">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button icon="plus" type="primary" @click="handleAdd">新增</a-button>
        <a-button icon="download" type="primary" @click="handleExportXls('设备实例')">导出</a-button>
        <a-upload :action="importExcelUrl" :headers="tokenHeader" :multiple="false" :showUploadList="false" name="file" @change="handleImportExcel">
          <a-button icon="import" type="primary">导入</a-button>
        </a-upload>
        <a-button icon="reload" type="" @click="refreshCache()">刷新缓存</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="batchDel">
              <a-icon type="delete" />
              删除
            </a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <!-- table区域-begin -->
      <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>

        <a-table
          :columns="columns"
          :dataSource="dataSource"
          :expandedRowKeys="expandedRowKeys"
          :loading="loading"
          :pagination="false"
          :rowSelection="{ fixed: true, selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          size="middle"
          @expandedRowsChange="handleExpandedRowsChange"
        >
          <template slot="sceneSlot" slot-scope="sceneId">
            <span v-for="scene in sceneOptions" :key="scene.id">
              <span v-if="scene.id === sceneId" title="scene.id">{{ scene.name }}</span>
            </span>
          </template>
          <template slot="sceneSchemeSlot" slot-scope="sceneSchemeId">
            <span v-for="sceneScheme in sceneSchemeOptions" :key="sceneScheme.id">
              <span v-if="sceneScheme.id === sceneSchemeId" title="sceneScheme.id">{{ sceneScheme.name }}</span>
            </span>
          </template>
          <template slot="statusSlot" slot-scope="text, record">
            <li v-show="record.state === 'online'">
              <a-icon :title="record.stateText" style="color:green;" theme="filled" type="check-circle" />
              在线
            </li>
            <li v-show="record.state === 'notActive'">
              <a-icon :title="record.stateText" style="color:gray" theme="filled" type="close-circle" />
              未激活
            </li>
            <li v-show="record.state === 'offline'">
              <a-icon :title="record.stateText" style="color:red" theme="filled" type="exclamation-circle" />
              离线
            </li>
          </template>
          <span slot="action" slot-scope="text, record">
            <a @click="handleDetail(record)">查看</a>
            <a-divider type="vertical" />
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
              <a>删除</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a-popconfirm @confirm="setStatus(record.id)">
              <p slot="title">确定执行{{ record.state === 'notActive' ? '激活' : '注销' }}操作吗?</p>
              <a>{{ record.state === 'notActive' ? '激活' : '注销' }}</a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
      <device-instance-drawer ref="modalForm" @ok="modalFormOk"></device-instance-drawer>
      <device-instance-detail ref="modalDetail"></device-instance-detail>
    </a-card>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@api/manage'
import DeviceInstanceDrawer from './modules/DeviceInstanceDrawer.vue'
import JTreeSelect from '@/components/jeecg/JTreeSelect'
import DeviceInstanceDetail from '@views/iotcp/device/instance/DeviceInstanceDetail'

export default {
  name: 'DeviceInstanceList',
  mixins: [JeecgListMixin],
  components: {
    DeviceInstanceDetail,
    DeviceInstanceDrawer,
    JTreeSelect
  },
  data() {
    return {
      description: '设备实例管理页面',
      timer: null,
      modelSelect: undefined,
      modelOptions: [],
      sceneOptions: [],
      sceneSchemeOptions: [],
      stateCount: {},
      loading: false,
      detailRoute: '',
      // 展开的行，受控属性
      expandedRowKeys: [],
      // 表头
      columns: [
        {
          title: '实例名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '设备类型',
          align: 'center',
          dataIndex: 'deviceTypeText',
          key: 'deviceTypeText'
        },
        {
          title: '所属场景',
          align: 'center',
          dataIndex: 'sceneBy',
          key: 'sceneBy',
          scopedSlots: { customRender: 'sceneSlot' }
        },
        {
          title: '场景方案',
          align: 'center',
          dataIndex: 'sceneSchemeBy',
          key: 'sceneSchemeBy',
          scopedSlots: { customRender: 'sceneSchemeSlot' }
        },
        {
          title: '子设备',
          align: 'center',
          dataIndex: 'children',
          key: 'children',
          customRender: function(t, r, index) {
            return !t ? 0 : t.length
          }
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'state',
          key: 'state',
          scopedSlots: { customRender: 'statusSlot' }
        },
        {
          title: '创建日期',
          align: 'center',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        listModel: '/device/model/listAll',
        listScene: '/scene/manage/listAll',
        listSceneScheme: '/scene/sceneScheme/listAll',
        list: '/device/instance/listTree',
        delete: '/device/instance/delete',
        deleteBatch: '/device/instance/deleteBatch',
        exportXlsUrl: '/device/instance/exportXls',
        importExcelUrl: 'device/instance/importExcel',
        setStatus: 'device/instance/setStatus',
        refreshCache: 'device/instance/refreshCache'
      },
      dictOptions: {}
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  mounted() {
    this.loadModel()
    this.loadScene()
    this.loadSceneScheme()
  },
  methods: {
    refreshCache() {
      let that = this
      getAction(this.url.refreshCache, {}).then(res => {
        if (res.success) {
          that.$message.success('刷新缓存成功！')
        }
      })
    },
    getStateCount(value) {
      let scope = this
      console.log(value)
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        scope.dataSource = []
        getAction(this.url.list, { modelBy: value }).then(res => {
          if (res.success) {
            scope.dataSource = res.result
            scope.stateCount = JSON.parse(res.message)
          }
        })
      }, 300)
    },
    // 加载所有模型
    loadModel() {
      let scope = this
      this.dataSource = []
      getAction(this.url.listModel).then(res => {
        if (res.success) {
          scope.modelOptions = res.result
        }
      })
    },
    // 加载所有场景信息
    loadScene() {
      let scope = this
      getAction(this.url.listScene).then(res => {
        if (res.success) {
          scope.sceneOptions = res.result
        }
      })
    },
    // 加载所有场景方案信息
    loadSceneScheme() {
      let scope = this
      getAction(this.url.listSceneScheme).then(res => {
        if (res.success) {
          scope.sceneSchemeOptions = res.result
        }
      })
    },
    loadData() {
      let scope = this
      this.dataSource = []
      getAction(this.url.list, this.getQueryParams()).then(res => {
        if (res.success) {
          scope.dataSource = res.result
          scope.stateCount = JSON.parse(res.message)
        }
      })
    },
    getDetailRoute() {
      let scope = this
      getAction('/device/instance/getDetailRoute').then(data => {
        if (data.success) {
          scope.detailRoute = data.result
        }
      })
    },
    handleDetail(record) {
      // this.$router.push({
      //   path: `/device/instance/${record.id}`,
      // })
      // this.$router.push({path: `/device/instance/${record.id}`})

      this.$refs.modalDetail.detail(record.id)
    },
    handleAdd() {
      this.$refs.modalForm.title = '添加设备实例'
      this.$refs.modalForm.add()
    },
    handleEdit(record) {
      this.$refs.modalForm.title = '设备实例'
      console.log(record)
      this.$refs.modalForm.edit(record)
    },
    setStatus(id) {
      var that = this
      getAction(this.url.setStatus, { id: id }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    initDictConfig() {},
    handleExpandedRowsChange(expandedRows) {
      this.expandedRowKeys = expandedRows
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
